package controller;

import java.util.ArrayList;

import manager.BidMgr;
import manager.StudentMgr;
import controller.validator.BidValidator;
import entity.Bid;
import entity.Round;
import exception.InputValidationErrors;

/**
 * @author huangjm.2012, jaslin.wee.2012, sheryl.tay.2012, mohameds.2012,
 *         huiwensong.2012
 * 
 */

public class BidCtrl {

	private BidMgr bidMgr = new BidMgr();
	private StudentMgr studentMgr = new StudentMgr();
	private RoundCtrl roundCtrl = new RoundCtrl();

	public void add(Bid bid) {
		bidMgr.addBid(bid);
		studentMgr.updateEdollarForStudent(
				bid.getStudent().getEdollar() - bid.getBidAmount(), bid
						.getStudent().getUserId());

		if (roundCtrl.isCurrentRoundNo(Round.ROUND_TWO)) {
			roundCtrl.computeAndStoreMinBidAmountForSectionInRoundTwo(bid
					.getSection());
		}
	}

	public void updateBid(String userId, String courseCode, String sectionCode,
			String bidAmountStr) throws InputValidationErrors {

		BidValidator bidValidator = new BidValidator(userId, courseCode,
				sectionCode, bidAmountStr);
		bidValidator.performValidationBeforeUpdating();
		Bid bid = bidValidator.getBid();

		bidMgr.deleteBid(bid.getStudent().getUserId(), bid.getSection()
				.getCourse().getCourseCode());
		bidMgr.addBid(bid);
		studentMgr.updateEdollarForStudent(bidValidator
				.getUpdatedEdollarForStudent(), bid.getStudent().getUserId());

		if (roundCtrl.isCurrentRoundNo(Round.ROUND_TWO)) {
			roundCtrl.computeAndStoreMinBidAmountForSectionInRoundTwo(bid
					.getSection());
		}
	}

	public boolean deleteBid(String userId, String courseCode,
			String sectionCode) throws InputValidationErrors {

		BidValidator bidValidator = new BidValidator(userId, courseCode,
				sectionCode);
		bidValidator.performValidationBeforeDeleting();

		boolean isDeleted = bidMgr.deleteBid(userId, courseCode, sectionCode);
		studentMgr.updateEdollarForStudent(
				bidValidator.getUpdatedEdollarForStudent(), userId);

		return isDeleted;
	}

	public ArrayList<Bid> retrieveAllBidsForStudent(String userId) {
		return bidMgr.retrieveAllBidsForStudent(userId);
	}

	public ArrayList<Bid> retrievePendingBidsForStudent(String userId) {
		return bidMgr.retrievePendingBidsForStudent(userId);
	}

	public ArrayList<Bid> retrieveBidsForSections(String courseCode,
			String sectionCode) {
		return bidMgr.retrieveBidsForSection(courseCode, sectionCode);
	}

	public Bid retrieveBid(String courseCode, String sectionCode, String userId) {
		return bidMgr.retrieveBid(courseCode, sectionCode, userId);
	}

}
